package com.bjfu.intelligentrecognizeserver.controller;

import com.bjfu.intelligentrecognizeserver.Util.JwtUtil;
import com.bjfu.intelligentrecognizeserver.common.constant.JwtClaimsConstant;
import com.bjfu.intelligentrecognizeserver.common.Result;
import com.bjfu.intelligentrecognizeserver.pojo.dto.UserLoginDTO;
import com.bjfu.intelligentrecognizeserver.pojo.dto.UserRegisterDTO;
import com.bjfu.intelligentrecognizeserver.pojo.entity.User;
import com.bjfu.intelligentrecognizeserver.pojo.vo.UserInfoVo;
import com.bjfu.intelligentrecognizeserver.pojo.vo.UserLoginVo;
import com.bjfu.intelligentrecognizeserver.properties.JwtProperties;
import com.bjfu.intelligentrecognizeserver.service.UserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user")
@RequiredArgsConstructor
@Slf4j
public class UserController {

    private static final Logger LOGGER = LoggerFactory.getLogger(UserController.class);

    private final UserService userService;
    private final JwtProperties jwtProperties;

    @RequestMapping("/login")
    public Result<UserLoginVo> login(@RequestBody UserLoginDTO userLoginDTO) {
        LOGGER.info(userLoginDTO.toString());
        User user = userService.login(userLoginDTO);

        //登录成功后，生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID, user.getId());
        String token = JwtUtil.generateJwt(
                jwtProperties.getUserSecretKey(),
                jwtProperties.getUserTtl(),
                claims
        );

        UserLoginVo userLoginVo = UserLoginVo.builder()
                .id(user.getId())
                .username(user.getUsername())
                .phone(user.getPhone())
                .token(token)
                .image(user.getImage())
                .password(user.getPassword())
                .build();


        //登录成功，生成jwt令牌
        return Result.success(userLoginVo);
    }

    @RequestMapping("/register")
    public Result<Object> register(@RequestBody UserRegisterDTO userRegisterDTO) {
        int res = userService.register(userRegisterDTO);
        if (res == 0) {
            return Result.error("当前用户已经存在");
        }
        return Result.success();
    }

    @RequestMapping("/getUserInfo")
    public Result<UserInfoVo> getUserInfo(){
        log.info("getUserInfo");
        UserInfoVo userInfoVo = userService.getUserInfo();
        return Result.success(userInfoVo);
    }
}
